//
//  FirstViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/15.
//  Copyright (c) 2015年 YAX. All rights reserved.
//
#import "FirstViewController.h"
#import "SDCycleScrollView.h"
#import "HeaderView.h"
#import "ITHomePublicModel.h"
#import "HeaderWebViewController.h"
#define kFirstViewTabel @"FirstViewTabel" //首页推荐 离线表

#define Kheader @"http://www.36kr.com/api/v1/topics/feature.json?token=734dca654f1689f727cc:32710"
#define KHomeCellUrl @"http://www.36kr.com/api/v1/topics.json?token=734dca654f1689f727cc:32710&page=1&per_page=20"
#define KWebHeader @"http://rong.36kr.com/api/v1/news/%@"

@interface FirstViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)NSMutableArray *images;
@property(nonatomic,strong)NSMutableArray *titles;
@property(nonatomic,strong)NSMutableArray *modelArray;
@property(nonatomic,strong)NSMutableArray *IDArray;

@property(nonatomic,strong)NSMutableArray *headerModelArray; //轮播图数组

@property(nonatomic,assign)int pages;
@end

@implementation FirstViewController


- (NSMutableArray *)modelArray
{
    if (!_modelArray) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.pages = 20;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 30 - 64 - 49) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tableView];
    
    [self getHeaderViewRequest];

//    [self getRequest];
    
    // 进来自动刷新
    [self downRefresh];

    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    // 上拉提载
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
}

//数据本地化：
//1.有一个匹配数据库表，数据中存取所需要的数据。（只存20条数据）
//2.在初次数据解析的时候，创建表格 - 插入数据 以后进入解析前先判断数据库中是否有数据,有就直接把数据库中的数据添加到试图上,没有就解析。
//3.下拉刷新处理：下拉刷新时做个网络判断如果没网则不清空数据库（避免现在退出下次进来就没数据了）,如果有网络则清除数据库中的老数据，添加新的20条数据。
//4.上拉加载处理：上拉加载时不做数据库清空，只把加载出来的数据再添加到数据库中（也可以不做操作）。

//5.此方法与直接在解析数据处做网络判断的不同是：此方法不管是否有网络都先加载本地的数据，而直接在解析出做网络判断是有网就解析没网就本地。 -》 好处，加载数据快，省点流量。

// 下拉刷新()
- (void)downRefresh
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    // 如果有网
    if ([r currentReachabilityStatus] != NotReachable)
    {
        [FMDBManage deleteAllDatabaseTable:kFirstViewTabel];   //刷新成功后再移除数据库中数据。
        [self getRequest];
    }
    else
    {
         [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭, 请检查网络"];
    }
}

// 上拉加载
- (void)upRefresh
{
    self.pages += 20;
    NSString *url = [NSString stringWithFormat:@"http://www.36kr.com/api/v1/topics.json?token=734dca654f1689f727cc:32710&page=1&per_page=%d",self.pages];
    [LORequestManger GET:url success:^(id response) {
        [self.modelArray removeAllObjects];
        NSArray *bigArray = (NSArray *)response;
        for (NSDictionary *dic in bigArray)
        {
            ITHomePublicModel *model = [ITHomePublicModel itHomePubicModelWithDictionary:dic];
            [self.modelArray addObject:model];
        }
        [self.tableView reloadData];
         [self.tableView.header endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭, 请检查网络"];
    }];
//    [self.tableView.footer endRefreshing];
}

// cell加载
- (void)getRequest
{
    
//    [FMDBManage createDatabaseTabel:kFirstViewTabel];
//     NSMutableArray *arr = [FMDBManage selectAllDatabaseTable:kFirstViewTabel];
//    YAXLog(@"%@",arr);
//    if (arr.count != 0)
//    {
//        self.modelArray = [arr mutableCopy];
//    }
//    else
//    {
        [LORequestManger GET:KHomeCellUrl success:^(id response) {
            NSArray *bigArray = (NSArray *)response;
            [self.modelArray removeAllObjects];
            for (NSDictionary *dic in bigArray)
            {
               ITHomePublicModel *model = [ITHomePublicModel itHomePubicModelWithDictionary:dic];
                
                //插入数据库，以备离线用。
                [FMDBManage insertCacheTable:kFirstViewTabel Title:model.title created_at:model.created_at replies_count:model.replies_count featureImageUrl:model.feature_img];
          
                [self.modelArray addObject:model];
            }
            [self.tableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        }];
    }
    [self.tableView.header endRefreshing];
}

// 轮播图加载
- (void)getHeaderViewRequest
{
    [LORequestManger GET:Kheader success:^(id response) {
        NSArray *bigArray = (NSArray *)response;
        self.images = [NSMutableArray array];
        self.titles = [NSMutableArray array];
        self.IDArray = [NSMutableArray array];
        
        self.headerModelArray = [NSMutableArray array]; //轮播图model数组
        
        for (NSDictionary *dic in bigArray) {
            HeaderView *model = [HeaderView modelWithDict:dic];
            model.ID = dic[@"id"];
            [self.images addObject:model.feature_img];
            [self.titles addObject:model.excerpt];
            [self.IDArray addObject:model.ID];
            [self.headerModelArray addObject:model];
            
        }
        [self setSdCycleScrollView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}

// 轮播图代理方法
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    HeaderWebViewController *headerWeb = [[HeaderWebViewController alloc]init];
    headerWeb.urlString = [NSString stringWithFormat:@"http://rong.36kr.com/api/v1/news/%@",self.IDArray[index]];
//    YAXLog(@"%@", headerWeb.urlString);
    
    // 获取model
    HeaderView *model = self.headerModelArray[index];
    headerWeb.commentsCount = [NSString stringWithFormat:@"%@",model.replies_count]; // 评论数
    headerWeb.url = model.url; // 文章的url
    // 模态过去
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:headerWeb];
    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)setSdCycleScrollView
{
    //网络加载 --- 创建带标题的图片轮播器
    SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenIp6(250)) imageURLStringsGroup:nil]; // 模拟网络延时情景
    cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    cycleScrollView2.delegate = self;
    cycleScrollView2.titlesGroup = self.titles;
    cycleScrollView2.dotColor = [UIColor RGBColor:71 green:128 blue:208 alpha:1]; // 自定义分页控件小圆标颜色
    cycleScrollView2.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    self.tableView.tableHeaderView = cycleScrollView2;
    cycleScrollView2.imageURLStringsGroup = self.images;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView registerClass:[ITHomePublicTableViewCell class] forCellReuseIdentifier:@"cell"];
    ITHomePublicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    ITHomePublicModel *model = self.modelArray[indexPath.row];
    [cell loadCellWithDataModel:model];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kScreenIp6(90);
}

// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    HeaderWebViewController *header = [[HeaderWebViewController alloc]init];
    ITHomePublicModel *model = self.modelArray[indexPath.row];
    header.urlString = [NSString stringWithFormat:@"http://rong.36kr.com/api/v1/news/%@",model.ID];
    header.urlId = [NSString stringWithFormat:@"%@",model.ID]; //id 拼接
    header.commentsCount = [NSString stringWithFormat:@"%@",model.replies_count]; // 评论数
    header.url = [NSString stringWithFormat:@"http://36kr.com/p/%@.html", model.ID]; // 分享的Url
        header.feature_img = model.feature_img;
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:header];
    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nav animated:YES completion:nil];
        
}

#pragma mark - 内容警告提示
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}



@end
